angular.module('starter.services', [])

/**
 * Http请求
 */
.service('CrmHttp', ['$rootScope', '$http', '$q', 'Settings','$cordovaToast', function ($rootScope, $http, $q, Settings,$cordovaToast) {
    // 验证是否登录
    /*var isLogin = function(url) {
        if (url.indexOf('crm/app/login') < 0) {
            var loginInfo = Login.getLoginInfo();
            if (!loginInfo || !loginInfo.token) {
                $rootScope.openLoginModal();
                return false;
            }
        } else {
            return false;
        }
        return true;
    };*/

    var isLogin = function(result) {
        if (result && !result.success && result.errCode === 'NO_AUTHENTICATION') {
            $rootScope.autoLoginFunc();
        }
    };
    return {
        post: function (url, params) {
            if (!params.isLogin) {
                params.token = Login.getLoginInfo().token;
            }
            url = Settings.Context.path + url;
            var deferred = $q.defer();
            return $http.post(url, params, {timeout: 10000})
                .success(function (result) {
                    isLogin(result);
                    deferred.resolve(result);
                })
                .error(function (error) {
                    isLogin(error);
                    deferred.reject(error);
                });
            return deferred.promise;
        },
        get: function (url) {
            url = Settings.Context.path + url;
            if (url.indexOf('?') > 0) {
                url += '&token=' + Login.getLoginInfo().token;
            } else {
                url += '?token=' + Login.getLoginInfo().token;
            }
            var deferred = $q.defer();
            return $http.get(url)
                .success(function (result) {
                    isLogin(result);
                    deferred.resolve(result);
                })
                .error(function (error) {
                    isLogin(error);
                    deferred.reject(error);
                });
            return deferred.promise;
        }
    };
}])

// 七牛上传
.service('QiniuUploadToken', ['CrmHttp', function(CrmHttp) {
    var token = Login.getQiniUploadToken();
    if (!token || !token.dateTime || (new Date().getTime() - token.dateTime > 1800000)) {
        CrmHttp.get('/qiniu/getSimpleUploadToken').then(function(resultData) {
            var result = resultData.data;
            Login.setQiniUploadToken({
                token: result.attribute,
                dateTime: new Date().getTime()
            });
            token = Login.getQiniUploadToken();
        }, function(error) {
            console.log(JSON.stringify(error));
        })
    }
    return {
        getQiniuUploadToken: function() {
            return token.token;
        }
    };
}])
// 强制变更密码
.service('PasswordCheckService', ['CrmHttp', '$ionicPopup', '$rootScope', function(CrmHttp, $ionicPopup, $rootScope) {
    return {
        checkPasswordSecurity: function() {
            var url = "";
            var act = "";
            var params = {

            };
            return CrmHttp.post(url + act, params).then(
                function(result){
                    $rootScope.passwordSafetyChecked = true;
                    if (result) {
                        $rootScope.passwordSafety = true;
                    } else {
                        $rootScope.passwordSafety = false;
                        // 弹出提醒
                        PasswordCheckService.popupPasswordWarning();
                    }
                },
                function (error) {
                    $rootScope.passwordSafetyChecked = true;
                    setTimeout(function () {
                        $rootScope.passwordSafetyChecked = false;
                    }, 10000)
                }
            );
        },
        popupPasswordWarning: function () {
            $ionicPopup.confirm({
                title: '密码修改提醒',
                template: '您的密码强度过低，请立即修改',
                cancelText:'知道了',
                cancelType:'button-block button-outline button-energized-crm',
                okText: '修改',
                okType: 'button-block button-energized-crm',
            }).then(function(res) {
                if(res) {
                    $rootScope.openLoginForgetModal("修改密码", true);
                } else {
                    //
                }
            });
        }
    };
}])
.factory("versionUpdateService", function ($rootScope, $ionicPopup, $ionicDeploy, $timeout, $ionicLoading, $q, CrmHttp) {

    var version;
    var checkSuccess;

    /**
     * 获得version
     */
    function getAppVersion() {

        return $ionicDeploy.info().then(function (data) {
            var binaryVersion = data.binary_version; //大版本号
            var deployUuid = data.deploy_uuid; //小版本号
            deployUuid = deployUuid.indexOf('NO_DEPLOY_') < 0 ? deployUuid : '0';
            version = {
                'binary': binaryVersion,
                'deploy': deployUuid
            };
        });

        //return $ionicDeploy.info().then(function (data) {
        //    var binaryVersion = data.binary_version;
        //    var deployUuid = data.deploy_uuid;
        //    version =  deployUuid.indexOf('NO_DEPLOY_') < 0 ? deployUuid : binaryVersion;
        //});

    }

    /**
     * 检查是否需要更新package
     */
    function checkPackageVersion() {
        var deferred = $q.defer();

        if (!version) {
            deferred.resolve(false);
            return deferred.promise;
        }

        try {
            var url = '/crm/ver/';
            var act = 'update-app-store/check';
            var params = {
                'appId': 'lezhu-crm',
                'appVersion': version.binary,
                'devicePlatform': ionic.Platform.platform()
            };
            CrmHttp.post(url + act, params).then(
                function (result) {
                    deferred.resolve((result.data && result.data.updateAppStore) || false);
                },
                function (error) {
                    deferred.reject(error);
                }
            );
        } catch (e) {
            deferred.resolve(false);
        }

        return deferred.promise;
    }


    /**
     * 检查更新
     */
    function checkUpdate(isAuto) {
        !isAuto && $ionicLoading.show({
            template: '正在检查更新...',
            animation: 'fade-in',
            showBackdrop: true,
            duration: 3000,
            showDelay: 0
        });

         return $ionicDeploy.check().then(function (hasUpdate) {
            if (isAuto) {
                if (hasUpdate) {
                    update();
                } else {
                    checkSuccess = true;
                }
            } else {
                checkSuccess = true;
                if (hasUpdate) {
                    showUpdateConfirm();
                } else {
                    !isAuto && $ionicLoading.show({
                        template: '已经是最新版本!',
                        animation: 'fade-in',
                        showBackdrop: true,
                        duration: 2000,
                        showDelay: 0
                    });
                }
            }
        }, function (err) {
             checkSuccess = isAuto ? false : true;
             !isAuto && $ionicLoading.show({
                 template: '更新失败,请检查您的网络配置!' + err,
                 animation: 'fade-in',
                 showBackdrop: true,
                 duration: 2000,
                 showDelay: 0
             });
        });
    };

    function init() {
    };

    function showUpdateConfirm() {
        $ionicLoading.hide();
        var confirmPopup = $ionicPopup.confirm({
            title: '版本升级',
            template: "有新的版本了,是否要升级?",
            cancelText: '取消',
            okText: '升级'
        });
        confirmPopup.then(function (res) {
            if (res) {
                update();
            }
        });
    };

    function updateAppstorePackage() {
        $ionicPopup.alert({
            title: '升级提醒',
            template: '该版本已不能使用，请到应用商店安装新的版本',
            okText: '确定'
        }).then(function(res) {

            if(res) {
                if (window.cordova && window.cordova.ThemeableBrowser) {
                    cordova.ThemeableBrowser.open('http://a.app.qq.com/o/simple.jsp?pkgname=com.fangbaba.crm', '_blank', {
                        toolbar: {
                            height: 44,
                            color: '#f0f0f0ff'
                        },
                        title: {
                            color: '#111',
                            staticText: '版本升级',
                            showPageTitle: true
                        },
                        closeButton: {
                            wwwImage: 'img/CLOSE_32px_1162328_easyicon.net.png',
                            wwwImageDensity: 2,
                            align: 'right',
                            event: 'closePressed'
                        }
                    });
                }
            } else {
                //
            }
        });
    };

    function update() {
        $ionicLoading.show({
            template: '正在更新...',
            animation: 'fade-in',
            showBackdrop: true,
            //duration: 2000,
            showDelay: 0
        });

         return $ionicDeploy.update().then(function () {
            $ionicLoading.hide();
            $ionicLoading.show({
                template: '更新成功!',
                animation: 'fade-in',
                showBackdrop: true,
                duration: 2000,
                showDelay: 0
            });
        }, function (err) {
            $ionicLoading.hide();
            $ionicLoading.show({
                template: '更新失败!' + err,
                animation: 'fade-in',
                showBackdrop: true,
                duration: 2000,
                showDelay: 0
            });
        }, function (downloadProgress) {
            $ionicLoading.show({
                template: "已经下载：<span style='width: 50px;display: inline-block;'>" + Math.floor(parseInt(downloadProgress)) + "%</span>"
            });
            if (downloadProgress > 99) {
                $ionicLoading.hide();
            }
        });
    };


    return {
        init: function () {
            self = this;
            return getAppVersion();
        },

        getVersion: function () {
            return version;
        },

        checkSuccess: function () {
            return checkSuccess;
        },

        check: function (isAuto) {
            checkPackageVersion().then(function (updateAppStore) {
                if (updateAppStore) {
                    checkSuccess = true;
                    $rootScope.updateAppStore = true;
                    updateAppstorePackage(); //强制更新大版本
                } else {
                    checkUpdate(isAuto); //强制更新小版本
                }
            }, function () {
                checkSuccess = true;
                setTimeout(function(){
                    checkSuccess = false;
                }, 10000); //一段时间后重新检查
            });
        },

        //checkPackage: function () {
        //    return checkPackageVersion();
        //},

        //checkUpdate: function (isAuto) {
        //    return checkUpdate(isAuto);
        //},

        updatePackage: function () {
            return updateAppstorePackage();
        },

        update: function () {
            return update();
        }
    }
})
.filter('asterisk', function() {
    return function (input, params1, params2, params3) {
        if (input) {
            var len = input.length;
            if (len < params1 || len < params2 || len < params3) {
                return input;
            }
            var starStr = input.substr(0, params1);
            var asterisk = [];
            for (var i = 0 ; i < params2; i++) {
                asterisk.push('*');
            }
            var endStr = input.substr(len - params3 - 1, params3);
            return starStr + asterisk.join('') + endStr;
        }
        return input;
    };
})

.filter('replace2char', function() {
    return function (input, params1, params2) {
        var rtnStr = '';
        if (input) {
            var len = input.length;
            if (len > params2 && params2 > 0) {
                var chars = input.split('');
                for (var i = 0; i < chars.length; i++) {
                    rtnStr += chars[i];
                    if (i % params2 === params2 - 1 && i + 1 < chars.length) {
                        rtnStr += params1;
                    }
                }
            }
        }
        return rtnStr;
    };
});
